from tkinter import *
from tkinter import messagebox
from pathlib import Path

import pymysql

from gui.main_window.server import settings

# OUTPUT_PATH = Path(__file__).parent
# ASSETS_PATH = OUTPUT_PATH / Path("./img")
# def relative_to_assets(path: str) -> Path:
#     return ASSETS_PATH / Path(path)
class Notpassword ():

    def __init__(self,root,photo2):
        # self.root = Tk() # 本地模式使用
        self.root1 = root
        root.attributes('-disabled', 1)
        self.root = Toplevel(root)
        self.root.title("找回密码")
        self.root.config(background="white")
        self.root.resizable(0, 0)
        root_height = 350
        root_width = 460
        sx = self.root.winfo_screenwidth()
        sy = self.root.winfo_screenheight()
        cw_x = (sx - root_width) / 2
        cw_y = (sy - root_height) / 2
        self.root.geometry("%dx%d+%d+%d" % (root_width, root_height, cw_x, cw_y))

        # photo0 = PhotoImage(file=relative_to_assets("jantu.png"))

        self.ver_random = '1'

        self.canvas_top = Canvas(
            self.root,
            bg="white",
            height=2,
            width=180,
            bd=0,
            highlightthickness=0,
            relief="ridge",
        )
        self.canvas_top.pack(side=TOP, fill=Y)
        Label(self.canvas_top,text = "找回密码", font=("宋", 15, "bold"), fg="#32CDFA",bg = "white").grid(row=0, column=0,
                                                                                           pady = 15)
        Canvas(self.canvas_top,bg ="#32CDFA" ,width = 320,height = 2,relief="ridge" ,bd = 0,highlightthickness=0,).grid(row=1, column=0,
                                                                                           )
        frame0 = Frame(self.root, bg="white", relief="flat", height=20, width=20)
        frame0.pack(side=TOP, fill=Y,pady = 10)
        self.mailbox_l0 = Label(frame0,text = "1.邮箱验证",bg ="#32CDFA",fg = "white" )
        self.mailbox_l0.grid(row = 0,column = 0)
        Label(frame0,image = photo2,bg = "white").grid(row = 0,column = 1)
        self.pass_l0 = Label(frame0,text = "2.确认密码",bg = "#9bd6f4",fg = "white" )
        self.pass_l0.grid(row = 0,column = 2)

        self.canvas_top_2 = Canvas(
            self.root,
            bg="white",
            height=2,
            width=180,
            bd=0,
            highlightthickness=0,
            relief="ridge",)

        self.canvas_top_2.pack(side=TOP, fill=Y,pady = 20)

        self.canvas_top_1 = Canvas(
            self.root,
            bg="white",
            height=2,
            width=180,
            bd=0,
            highlightthickness=0,
            relief="ridge",
        )
        self.canvas_top_1.pack(side=TOP, fill=Y)
        self.cmailbox_l = Label(self.canvas_top_2, bg="white", fg="red", width=30)
        self.cmailbox_l.pack(side=TOP, fill=Y)

        mailbox_l = Label(self.canvas_top_1,bg = "white" , fg = "#32CDFA",text = "邮    箱:",width = 8)
        mailbox_l.grid(row = 0,column = 0,pady = 10,padx = 15)
        code_l = Label(self.canvas_top_1,bg = "white" , fg = "#32CDFA",text = "验证码:",width = 8)
        code_l.grid(row = 1,column = 0,pady = 10,padx = 15)

        self.new_mailbox = StringVar()
        code_e= Entry(self.canvas_top_1, bd=3,textvariable = self.new_mailbox )
        code_e.grid(row=0, column=1, pady=10, padx=15)
        mailbox_f = Frame(self.canvas_top_1, bg="white", relief="flat", height=20, width=20)
        mailbox_f.grid(row=1, column=1)

        self.new_mailbox_confirm = StringVar()
        mailbox= Entry(mailbox_f, bd = 3,width = 15,textvariable = self.new_mailbox_confirm)
        mailbox.pack(side = LEFT,fill = Y)


        self.send_b = Button(mailbox_f,command =lambda : self.verification(60),bg = "#32CDFA",fg = "white",text = "发送",relief="flat",bd = 0)
        self.send_b.pack(side = LEFT,fill = Y,padx = 3)
        next_b = Button(self.canvas_top_1,bg = "#32CDFA",fg = "white",text = "下一步",relief="flat",bd = 0,width = 20,command = self.nekststep)
        next_b.grid(row = 4,column = 0,columnspan=2,pady = 5)

        self.aal = [mailbox_l,code_l,code_e,mailbox_f,next_b]

        # 关闭子窗口时调用这个函数
        self.root.protocol('WM_DELETE_WINDOW',self.t_close)

        mailbox.bind("<Return>", self.nekststep)
        # self.root.mainloop()

    def verification(self, ti):
        self.cmailbox_l.config(text='')

        x_mailbox = self.new_mailbox.get()  # 获取邮箱输入框内容
        r_malibox = "^.+\\@(\\[?)[a-zA-Z0-9\\-\\.]+\\.([a-zA-Z]{2,3}|[0-9]{1,3})(\\]?)$"  # 邮箱处理
        result_malibox = re.match(r_malibox, x_mailbox)

        readmalibox_sql = f'''select * from b_user where mailbox = "{x_mailbox}"'''
        mailbox_data = settings.Mysql_c(readmalibox_sql)
        x_mailbox_data = mailbox_data.cursor_1()
        mailbox_data.close_conn()
        if not x_mailbox:
            self.cmailbox_l.config(text="!邮箱不能空")
        elif result_malibox is None:
            self.cmailbox_l.config(text="!邮箱格式错误")
        elif x_mailbox_data == False:
            self.cmailbox_l.config(text="!找不到此邮箱，请联系管理员")
        else:
            self.ver_random = settings.Random().code()
            self.ver_smtplib = settings.Smtplib(theme="找回密码", malibox=x_mailbox, value=self.ver_random)
            self.seconds = ti
            self.refresh_current_time()

    # 发送按钮显示60s函数
    def refresh_current_time(self):
        self.malibox_None = False
        self.send_b.config(state=DISABLED)

        """刷新当前时间"""
        if self.seconds > 0:

            self.send_b.config(text=str(self.seconds), width=3)
            self.seconds -= 1
            self.send_b.after(1000, self.refresh_current_time)
        else:
            self.send_b.config(state=NORMAL)
            self.send_b.config(text="发送", width=3)
            self.malibox_None = True

    # 下一步函数
    def nekststep(self,enter=''):
        self.cmailbox_l.config(text='')
        new_mailbox_confirm = self.new_mailbox_confirm.get()
        self.x_mailbox = self.new_mailbox.get()  # 获取邮箱输入框内容
        r_malibox = "^.+\\@(\\[?)[a-zA-Z0-9\\-\\.]+\\.([a-zA-Z]{2,3}|[0-9]{1,3})(\\]?)$"  # 邮箱处理
        result_malibox = re.match(r_malibox, self.x_mailbox)
        if not self.x_mailbox:
            self.cmailbox_l.config(text="!邮箱不能空")
        elif result_malibox is None:
            self.cmailbox_l.config(text="!邮箱格式错误")
        elif not new_mailbox_confirm:
            self.cmailbox_l.config(text="!请填入验证码")
        elif new_mailbox_confirm != self.ver_random:
            self.cmailbox_l.config(text="!验证码错误")
        elif self.malibox_None:
            self.cmailbox_l.config(text="!验证码已过期")
        else:
            self.resetpass()

    # 修改密码界面函数
    def resetpass(self):
        # self.x_mailbox = self.new_mailbox.get()  # 获取邮箱输入框内容 等下删除
        self.mailbox_l0.config(bg = "#9bd6f4")
        self.pass_l0.config(bg = "#32CDFA")

        for i in self.aal:
            i.grid_forget()

        self.new_passwd = StringVar()
        self.nota_passwd = StringVar()
        Label(self.canvas_top_1, bg="white", fg="#32CDFA", text="新密码:", width=8).grid(row=0, column=0, pady=10, padx=15)
        Label(self.canvas_top_1, bg="white", fg="#32CDFA", text="确认密码:", width=8).grid(row=1, column=0, pady=10, padx=15)
        a1 = Entry(self.canvas_top_1,textvariable = self.new_passwd, bd=3, )
        a1.grid(row=0, column=1, pady=10, padx=15)

        a2 = Entry(self.canvas_top_1,textvariable = self.nota_passwd, bd=3,)
        a2.grid(row=1, column=1, pady=10, padx=15)
        next_b = Button(self.canvas_top_1, command = self.amend,bg="#32CDFA", fg="white", text="确认修改", relief="flat", bd=0, width=20)
        next_b.grid(row=4, column=0, columnspan=2, pady=5)
        a2.bind('<Return>',self.amend)

    # 确认密码修改函数
    def amend(self,enter=''):
        self.cmailbox_l.config(text='')

        new_passwd = self.new_passwd.get()
        nota_passwd = self.nota_passwd.get()
        r = '^(?=.*?\d)(?=.*[a-z])[0-9a-z]{8,16}$'
        result_paw = re.match(r, new_passwd)
        if not new_passwd:
            self.cmailbox_l.config(text='请输入新密码')
        elif result_paw is None:
            self.cmailbox_l.config(text="!请输入8-16位密码,包含数字和字母")
        elif new_passwd != nota_passwd:
            self.cmailbox_l.config(text="!两次输入的密码不一样")
        else:
            pwdmd5 = settings.Md5(pwd=new_passwd)
            ser_password = pwdmd5.strmd5()
            try:
                sql = 'UPDATE b_user SET passwd=%s WHERE mailbox=%s'
                value = (ser_password, self.x_mailbox)
                sql_data = settings.Mysql_c(sql=sql,value=value)
                sql_data.commit()
                self.root1.attributes('-disabled', 0)
                messagebox.showinfo(title='恭喜', message='密码已找回请重新登录')
                self.root.destroy()

            except pymysql.Error as e:
                print(e)




    # 关闭子窗口取消锁主窗口函数
    def t_close(self):
        self.root1.attributes('-disabled', 0)
        self.root.destroy()


if __name__ == "__main__":
    Notpassword(1)
